package middleware

import (
	"fmt"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"gitee.com/enzolwb/my-web-scaffold/pkg/email"
	"gitee.com/enzolwb/my-web-scaffold/pkg/setting"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"runtime"
	"runtime/debug"
	"strings"
)

// RecoveryMiddleware捕获所有panic，并且返回错误信息
func RecoveryMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		if setting.ServerSetting.RunMode != "debug" {
			//正式环境需要捕获 并发送邮件
			defer func() {
				if err := recover(); err != nil {
					_, file, line, _ := runtime.Caller(2)
					c.Request.ParseForm()
					params := ""
					for k, v := range c.Request.PostForm {
						params += fmt.Sprintf("key:%v val:%v <br>", k, v)
					}
					data, _ := ioutil.ReadAll(c.Request.Body)
					params += fmt.Sprintf("Request.body: %v", string(data))
					//生产需要发邮件
					go func() {
						stack := debug.Stack()
						DebugStack := fmt.Sprintf("Method: %s,Host: %s,URI: %s,IP:%s <br>",
							c.Request.Method, c.Request.Host, c.Request.RequestURI, c.ClientIP())
						for _, s := range strings.Split(string(stack), "\n") {
							DebugStack += s + "<br>"
						}
						DebugStack += file + "<br>"
						DebugStack += fmt.Sprintf("line: %d <br>", line)
						DebugStack += params
						o := &email.Options{
							MailHost: setting.EmailSetting.HOST,
							MailPort: setting.EmailSetting.PORT,
							MailUser: setting.EmailSetting.USERNAME,
							MailPass: setting.EmailSetting.PASSWORD,
							MailTo:   setting.EmailSetting.ADMINMAIL, //管理员邮箱
							Subject:  fmt.Sprintf("项目%s,出现错误", setting.AppSetting.AppName),
							Body:     DebugStack,
						}
						o.Send()
					}()
				}
				app.Response(c, ecode.ErrServer)
				return
			}()
		}
		c.Next()
	}
}
